package com.cssl.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * MD加密工具
 */
public class UtilEncryption {

    private static final String SECRET_KEY = "ThisIsASecretKey"; // 密钥，必须是16、24或32字节长

    /**
     * 加密
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        // 创建 AES 密钥
        SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

        // 创建加密器
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 加密数据
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());

        // 将加密后的字节数组编码为 Base64 字符串
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密
     * @param encryptedText
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText) throws Exception {
        // 创建 AES 密钥
        SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");

        // 创建解密器
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        // 将 Base64 字符串解码为字节数组
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);

        // 解密数据
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 将解密后的字节数组转换为字符串
        return new String(decryptedBytes);
    }

    public static void main(String[] args) {
        try {
            String originalText = "root";

            // 加密
            String encryptedText = encrypt(originalText);
            System.out.println("Encrypted: " + encryptedText);

            // 解密
            String decryptedText = decrypt(encryptedText);
            System.out.println("Decrypted: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
